<?php

namespace app\apiadmin\controller\live;

use app\apiadmin\controller\liveManager\LiveStatus;
use app\apiadmin\model\behavior\LiveUserMongo;
use app\apiadmin\model\behavior\LiveUserMsgMongo;
use app\common\controller\BaseController;
use app\common\utils\Res;
use think\facade\Db;

class Screen extends BaseController
{
    public function illegal()
    {
        $liveId = $this->request->post('liveId') ?? 0;
        if (empty($liveId)) {
            return Res::error('直播ID不得为空');
        }

        $group = Db::name('siyu_live_manager_forbid')->where(['live_id' => $liveId])->select();
        $groupId = [];
        foreach ($group as $item) {
            $groupId[] = $item['group_id'];
        }
        $g_list = Db::name('siyu_yanjinci_group')->where('id', 'in', $groupId)->where('del', 0)->order('id desc')->select();
        $y_list = Db::name('siyu_yanjinci_list')->where('groupid', 'in', $groupId)->where('del', 0)->order('id desc')->select();
        $list = [];
        foreach ($y_list as &$item) {
            foreach ($g_list as $value) {
                if ($item['groupid'] == $value['id']) {
                    $item['group_name'] = $value['name'];
                }
            }
            $list[] = $item;
        }
        return Res::ok(['list' => $list, 'group' => $g_list]);

    }

    public function addIllegal()
    {

    }

    /**
     * @author: zwx
     * @Description: 点击商品人数
     * @Date: 2024-05-26 16:14:53
     */
    public function shujukanban()
    {
        $param = $this->request->post();

        //累计在线人数
        $liveId = $param['liveId'];

        // $res_data =  self::realStatisticsUser($liveId);

        $t = DB::table('xh_siyu_live_manager')->where(array('id' => $liveId))->find();

        $liveStatus = new LiveStatus($liveId);

        $data = array();

        // if($t['status']==1){
        //     $data['time'] = date('Y-m-d H:i:s');
        // }else if($t['status']==0){
        //     $data['time'] = $liveStatus->get_live_starttime();
        // }else{
        //     $data['time'] = $t['end_time'];
        // }
        $data['time'] = date('Y-m-d H:i:s');
        $data['start_time'] = $liveStatus->get_live_starttime();

        $data['dianji_shangpin_renshu'] = $liveStatus->get_dianji_shangpin_renshu() ? $liveStatus->get_dianji_shangpin_renshu() : 0; //点击商品人数
        $data['dianji_shangpin_cishu'] = $liveStatus->get_dianji_shangpin_cishu() ? $liveStatus->get_dianji_shangpin_cishu() : 0; //点击商品次数

        $data['zong_xiaoshoue'] = $liveStatus->get_xiaoshoue_yifukuan() ? number_format($liveStatus->get_xiaoshoue_yifukuan() / 100, 2) : 0; //已付款销售额
        $data['xiadan_reshu'] = $liveStatus->get_xiadan_rensu_yifukuan() ? $liveStatus->get_xiadan_rensu_yifukuan() : 0; //已付款人数
        $data['xiadan_danshu'] = $liveStatus->get_xiadan_danshu_yifukuan() ? $liveStatus->get_xiadan_danshu_yifukuan() : 0; //已付款单数

        $data['weizhifu_xiaoshoue'] = $liveStatus->get_xiaoshoue_weifukuan() ? number_format($liveStatus->get_xiaoshoue_weifukuan() / 100, 2) : 0; //未款销售额
        $data['weifukuan_renshu'] = $liveStatus->get_xiadan_renshu_weifukuan() ? $liveStatus->get_xiadan_renshu_weifukuan() : 0; //未付款人数
        $data['weizhifu_danshu'] = $liveStatus->get_xiadan_danshu_weifukuan() ? $liveStatus->get_xiadan_danshu_weifukuan() : 0; //未付款单数

        $data['tuikuan_xiaoshoue'] = $liveStatus->get_xiaoshoue_tuikuan() ? number_format($liveStatus->get_xiaoshoue_tuikuan() / 100, 2) : 0; //退款销售额
        $data['tuikuan_renshu'] = $liveStatus->get_xiadan_renshu_tuikuan() ? $liveStatus->get_xiadan_renshu_tuikuan() : 0; //退款人数
        $data['tuikuan_danshu'] = $liveStatus->get_xiadan_danshu_tuikuan() ? $liveStatus->get_xiadan_danshu_tuikuan() : 0; //退款单数

        // $data['zhibo_shichang'] = 0;
        // if(($liveStatus->get_live_endtime() && time()<strtotime($liveStatus->get_live_endtime())) && $liveStatus->get_live_starttime() && time()>strtotime($liveStatus->get_live_starttime())){
        //     $data['zhibo_shichang'] = time()-strtotime($liveStatus->get_live_starttime())>0 ? time()-strtotime($liveStatus->get_live_starttime()) : 0; //直播时长
        //     $liveStatus->set_zhibo_leiji_shichang($data['zhibo_shichang']);
        // }else if($liveStatus->get_live_starttime() && time()<strtotime($liveStatus->get_live_starttime())){
        //     $data['zhibo_shichang'] = 0; //直播时长
        //     $liveStatus->set_zhibo_leiji_shichang($data['zhibo_shichang']);
        // }

        // $data['guankan_renshu'] = $liveStatus->get_guankan_renshu() ? $liveStatus->get_guankan_renshu() : 0;   //累计观看人数

        //获取直播观看总时长
        //  $zongshicahng = $liveStatus->get_zhibo_leiji_shichang();

        //  //获取总人数
        //  $zongrenshu = $liveStatus->get_guankan_renshu();

        //  //记录平均观看时长
        //  if ($zongrenshu) {
        //     $pingjun = number_format($zongshicahng / $zongrenshu, 2);
        //  } else {
        //     $pingjun = 0;
        //  }

        //累计直播时长
        //  $data['zhibo_shichang'] = self::secondsToHoursAndMinutes($data['zhibo_shichang']);

        // $data['pingjun_guankan_shichang2'] = $pingjun ? $pingjun :'00:00:00';

        // if($pingjun){
        //     // 移除逗号
        //     $formatted_number = str_replace(',', '', $pingjun);
        //     // 移除小数点和后面的数字
        //     $integer_value = (int) floatval($formatted_number);
        //     $data['pingjun_guankan_shichang'] = $pingjun ? gmdate('H:i:s',$integer_value):'00:00:00';
        // }else{
        //     $data['pingjun_guankan_shichang'] = '00:00:00';
        // }

        $data['dianji_zhuanhualv'] = $data['dianji_shangpin_renshu'] ? number_format($data['xiadan_reshu'] * 100 / $data['dianji_shangpin_renshu'], 2) . '%' : '0.00%';

        // Screen::save_shujukanban($liveId);
        $data['state'] = $t['status'];
        //lyj-start
        $data['zhibo_shichang'] = '00:00:00';
        $zhibo_shichang = 0;
        switch ($t['status']) {
            case 1:
                $zhibo_shichang = time() - strtotime($data['start_time']);
                break;
            case 2:
                $zhibo_shichang = $t['service_end_time'] - $t['service_start_time'];
                break;
        }
        if ($zhibo_shichang) {
            $data['zhibo_shichang'] = self::secondsToHoursAndMinutes($zhibo_shichang);
            // $data['zhibo_shichang']=$zhibo_shichang;
        }
        $data['pingjun_guankan_shichang'] = '00:00:00';
        $data['guankan_renshu'] = 0;
        //本场累计观看总时长
        // $guankan_zong_shichang=$liveStatus->get_zong_guankan_shichang();//redis获取
        $guankan_zong_shichang = LiveUserMongo::user_sum($liveId, 'online_time'); //mogodb获取
        //累计观看人数
        $guankan_renshu = LiveUserMongo::user_count($liveId);
        if ($guankan_renshu) {
            $data['guankan_renshu'] = $guankan_renshu;
        }
        if ($guankan_renshu && $guankan_zong_shichang) {
            $data['pingjun_guankan_shichang'] = self::secondsToHoursAndMinutes($guankan_zong_shichang / $guankan_renshu);
        }
        //累计评论人数
//        $guankanArray = LiveUserMongo::list_array($liveId);
//        $guankanArr = array_column($guankanArray, 'live_user_id');
        $pinglunArray = LiveUserMsgMongo::user_list($liveId);
        $pinglunArr = [];
        foreach ($pinglunArray as $value) {
            if (is_numeric($value['live_user_id'])) {
                array_push($pinglunArr, $value['live_user_id']);
            }
        }
//        $pinglunArr = array_column($pinglunArray, 'live_user_id');
//        $pinglunArr = array_unique($pinglunArr);
        $data['pinglun_renshu'] = count(array_unique($pinglunArr));

        $data['interaction_lv'] = $guankan_renshu != 0 ? number_format($data['pinglun_renshu'] * 100 / $guankan_renshu, 2) . '%' : '0.00%';

        $invitation_user_data = \app\apiadmin\service\action\ActionService::getDaokekanban(['liveId' => $liveId]);
        $data['yaoyue'] = 0;
        $data['daoke'] = 0;
        $data['chengjiao'] = 0;
        $data['daokelv'] = 0;
        $data['chengjiaolv'] = 0;
        $data['yaoyuelv'] = 0;
        $invitation_user_data = json_decode($invitation_user_data->getContent(), true);
        if ($invitation_user_data && $invitation_user_data['code'] == 200) {
            $invitation_user_data = $invitation_user_data['data'];
            $data['yaoyue'] = $invitation_user_data['yaoyue'];
            $data['daoke'] = $invitation_user_data['daoke'];
            $data['chengjiao'] = $invitation_user_data['chengjiao'];
            $data['daokelv'] = $invitation_user_data['daokelv'];
            $data['chengjiaolv'] = $invitation_user_data['chengjiaolv'];
            $data['yaoyuelv'] = $invitation_user_data['yaoyuelv'];
        }
        // //lyj-end
        // $data['options']=[];
        // $data['optionsData']=[];
        // $optionsData=[];
        // $list=\app\apiadmin\model\behavior\LiveOnlineUserStatisticsMongo::list($liveId);
        // // dd($list);
        // if($list){
        //     foreach($list as $item){
        //         $timeZone = new \DateTimeZone('Asia/Shanghai');
        //         // $item->statistics_time->setTimezone($timeZone);
        //         $statistics_time=strtotime($item->statistics_time->toDateTime()->setTimezone($timeZone)->format('Y-m-d H:i:00'));
        //         // $statistics_time=$item->statistics_time->toDateTime()->setTimezone($timeZone)->format('Y-m-d H:i:00');
        //         $optionsData[$statistics_time]=$item->online_user_nums;
        //     }
        // }
        // // dd($optionsData);
        // $start_time=strtotime($t['start_time']);
        // $end_time=strtotime($t['end_time']);
        // if($start_time>time()){
        //     $start_time=time();
        // }
        // if($end_time>time()){
        //     $end_time=time();
        // }
        // $h=($end_time-$start_time)/3600;
        // $data['dataZoomStart']=0;
        // $data['dataZoomEnd']=number_format(100/$h,2);

        // for($start_time;$start_time<=$end_time;$start_time+=60){
        //     if(time()<$start_time)continue;
        //     $option_time = date('m-d H:i:00',$start_time);
        //     $data['options'][]=$option_time;
        //     $option_time=strtotime(date('Y-m-d H:i:00',$start_time));
        //     if(isset($optionsData[$option_time])){
        //         $data['optionsData'][]=$optionsData[$option_time];
        //     }else{
        //         $data['optionsData'][]=0;
        //     }
        //     $data['dataZoomStart']+=1;
        //     $data['dataZoomEnd']+=1;
        // }

        // $data['max']=max($data['optionsData']);
        // $data['splitNumber']=20;
        // while(true){
        //     if($data['max']==0){
        //         $data['max']=1;
        //     }
        //     $result = $data['max']%$data['splitNumber'];
        //     if($result==0){
        //         break;
        //     }
        //     $data['max']++;
        // }

        return Res::ok($data);
    }

    /**
     * @author: zwx
     * @Description: 点击商品人数
     * @Date: 2024-05-26 16:14:53
     */
    public static function save_shujukanban($liveId)
    {

        //累计在线人数
        $liveStatus = new LiveStatus($liveId);

        $data = array();

        $data['time'] = date('Y-m-d H:i:s');

        $data['liveId'] = $liveId;

        $data['start_time'] = $liveStatus->get_live_starttime();

        $data['dianji_shangpin_renshu'] = $liveStatus->get_dianji_shangpin_renshu() ? $liveStatus->get_dianji_shangpin_renshu() : 0; //点击商品人数
        $data['dianji_shangpin_cishu'] = $liveStatus->get_dianji_shangpin_cishu() ? $liveStatus->get_dianji_shangpin_cishu() : 0; //点击商品次数

        $data['xiaoshoue_yifukuan'] = $liveStatus->get_xiaoshoue_yifukuan() ? number_format($liveStatus->get_xiaoshoue_yifukuan() / 100, 2) : 0; //已付款销售额
        $data['xiadan_renshu_yifukuan'] = $liveStatus->get_xiadan_rensu_yifukuan() ? $liveStatus->get_xiadan_rensu_yifukuan() : 0; //已付款人数
        $data['xiadan_danshu_yifukuan'] = $liveStatus->get_xiadan_danshu_yifukuan() ? $liveStatus->get_xiadan_danshu_yifukuan() : 0; //已付款单数

        $data['xiaoshoue_weifukuan'] = $liveStatus->get_xiaoshoue_weifukuan() ? number_format($liveStatus->get_xiaoshoue_weifukuan() / 100, 2) : 0; //未款销售额
        $data['xiadan_renshu_weifukuan'] = $liveStatus->get_xiadan_renshu_weifukuan() ? $liveStatus->get_xiadan_renshu_weifukuan() : 0; //未付款人数
        $data['xiadan_danshu_weifukuan'] = $liveStatus->get_xiadan_danshu_weifukuan() ? $liveStatus->get_xiadan_danshu_weifukuan() : 0; //未付款单数

        $data['xiaoshoue_tuikuan'] = $liveStatus->get_xiaoshoue_tuikuan() ? number_format($liveStatus->get_xiaoshoue_tuikuan() / 100, 2) : 0; //退款销售额
        $data['xiadan_renshu_tuikuan'] = $liveStatus->get_xiadan_renshu_tuikuan() ? $liveStatus->get_xiadan_renshu_tuikuan() : 0; //退款人数
        $data['xiadan_danshu_tuikuan'] = $liveStatus->get_xiadan_danshu_tuikuan() ? $liveStatus->get_xiadan_danshu_tuikuan() : 0; //退款单数

        $data['zhiboshichang'] = time() - strtotime($liveStatus->get_live_starttime()) > 0 ? self::secondsToHoursAndMinutes((strtotime($liveStatus->get_live_endtime()) - strtotime($liveStatus->get_live_starttime()))) : 0; //直播时长

        $data['guankan_renshu'] = $liveStatus->get_guankan_renshu() ? $liveStatus->get_guankan_renshu() : 0; //累计观看人数

        $data['pingjun_guankan_shichang'] = $data['guankan_renshu'] ? number_format((time() - strtotime($liveStatus->get_live_starttime())) / $data['guankan_renshu'], 2) : 0;
        $data['dianji_zhuanhualv'] = $data['dianji_shangpin_renshu'] ? number_format($data['xiadan_renshu_yifukuan'] * 100 / $data['dianji_shangpin_renshu'], 2) . '%' : '0%';
        $t = DB::table('xh_siyu_live_tongji')->where(array('liveId' => $liveId))->find();
        if (!$t) {
            DB::table('xh_siyu_live_tongji')->insertGetId($data);
        } else {
            DB::table('xh_siyu_live_tongji')->where(array('liveId' => $liveId))->save($data);
        }

    }

    /**
     * @author: zwx
     * @Description: 秒数变时长
     * @param {*} $seconds
     * @Date: 2024-05-29 18:16:49
     */
    public static function secondsToHoursAndMinutes($seconds)
    {
        $seconds = round($seconds);
        $hours = floor($seconds / 3600);
        $minutes = floor(($seconds - ($hours * 3600)) / 60);
        $seconds = floor($seconds % 60);

        // 输出格式可以是 "00:00:00"
        return str_pad($hours, 2, '0', STR_PAD_LEFT) . ':' .
            str_pad($minutes, 2, '0', STR_PAD_LEFT) . ':' .
            str_pad($seconds, 2, '0', STR_PAD_LEFT);
    }

    /**
     * 直播在线实时人数统计
     * @param $liveId
     * @return \think\response\Json
     */
    public static function realStatistics2($liveId)
    {
        $result = [];
        if (empty($liveId)) {
            return Res::ok($result);
        }
        $user_list = \app\apiadmin\model\behavior\LiveUserMongo::user_list($liveId);
        if (!$user_list) {
            return Res::ok($result);
        }
        $res_data = [];
        $res_time = [];
        $res_value = [];
        foreach ($user_list as $value) {
            if ($value->online_status != 1) {
                continue;
            }
            $res_data[] = $value['last_enter_time']->toDateTime()->format('H:i:s');
            $res_time[] = $value['last_enter_time']->toDateTime()->format('H:i');
        }

        $result = array_unique($res_data);
        sort($result);
        $countValues = array_count_values($res_time);
        foreach ($countValues as $item) {
            $res_value[] = $item;
        }
        $data['realY'] = $result;
        $data['online_status'] = 1;
        $data['realX'] = $res_value;
        return Res::ok($data);
    }

    /**
     * 直播在线实时人数统计
     * @param $liveId
     * @return \think\response\Json
     */
    public static function realStatistics1($liveId)
    {
        $result = [];
        if (empty($liveId)) {
            return Res::ok($result);
        }
        $user_list = \app\apiadmin\model\behavior\LiveUserMongo::user_list($liveId);
        if (!$user_list) {
            return Res::ok($result);
        }
        $res_data = [];
        $res_time = [];
        $res_value = [];
        foreach ($user_list as $value) {
            if ($value->online_status != 1) {
                continue;
            }
            $res_data[] = $value['last_enter_time']->toDateTime()->format('H:i:s');
            $res_time[] = $value['last_enter_time']->toDateTime()->format('H:i');
        }

        $result = array_unique($res_data);
        sort($result);
        $countValues = array_count_values($res_time);
        foreach ($countValues as $item) {
            $res_value[] = $item;
        }
        $data['realY'] = $result;
        $data['online_status'] = 1;
        $data['realX'] = $res_value;
        return Res::ok($data);
    }
    public static function realStatistics($liveId)
    {
        $data = [
            'state' => 0,
            'options' => [],
            'optionsData' => [],
            'dataZoomStart' => 0,
            'dataZoomEnd' => 0,
            'max' => 0,
            'splitNumber' => 20,
        ];
        $t = DB::table('xh_siyu_live_manager')->where(array('id' => $liveId))->find();
        if (!$t) {
            return Res::ok($data);
        }
        // dd($t);
        $data['state'] = $t['status'];
        $optionsData = [];
        $inData = [];
        $outData = [];

        $list = \app\apiadmin\model\behavior\LiveOnlineUserStatisticsMongo::list($liveId);
        // dd($list);
        if ($list) {
            foreach ($list as $item) {
                //     $timeZone = new \DateTimeZone('Asia/Shanghai');
                //     $statistics_time=strtotime($item->statistics_time->toDateTime()->setTimezone($timeZone)->format('Y-m-d H:i:00'));
                $statistics_time = strtotime($item->statistics_time);
                $optionsData[$statistics_time] = $item->online_user_nums;
                $inData[$statistics_time] = $item->online_in;
                $outData[$statistics_time] = $item->online_out;

            }
        }
        // $optionsData = array_column($list,'online_user_nums','statistics_time');
        $start_time = strtotime($t['start_time']);
        if ($t['service_start_time']) {
            $start_time = $t['service_start_time'];
        }
        $end_time = strtotime($t['end_time']);
        if ($t['service_end_time']) {
            $end_time = $t['service_end_time'];
        }

        // end_time  此时不能小于 start_time
        // 如果发生这种情况一般情况下是 复制的问题
        if ($end_time < $start_time) {
            $end_time = strtotime($t['end_time']);
            $data["debug_info"]["use_liveinfo_end_time"] = [$end_time, $t['end_time']];
        }

        if ($start_time > time()) {
            $start_time = time();
        }
        if ($end_time > time()) {
            $end_time = time();
        }
        $h = ($end_time - $start_time) / 3600;
        $data["debug_info"]["start_end_time"] = [$start_time, $end_time, $end_time - $start_time];

        if ($h > 0) {
            $data['dataZoomEnd'] = round(100 / $h, 2);
        }

        for ($start_time; $start_time <= $end_time; $start_time += 60) {
            if (time() < $start_time) {
                continue;
            }

            $option_time = date('m-d H:i:00', $start_time);
            $data['options'][] = $option_time;
            $option_time = strtotime(date('Y-m-d H:i:00', $start_time));

            if (isset($optionsData[$option_time])) {
                $data['optionsData'][] = $optionsData[$option_time];

            } else {
                $data['optionsData'][] = 0;
            }

            if (isset($inData[$option_time])) {
                $data['inData'][] = $inData[$option_time];

            } else {
                $data['inData'][] = 0;
            }

            if (isset($outData[$option_time])) {
                $data['outData'][] = $outData[$option_time];

            } else {
                $data['outData'][] = 0;
            }

            $data['dataZoomStart'] += 1;
            $data['dataZoomEnd'] += 1;
        }

        $data['max'] = max($data['optionsData'] ? $data['optionsData'] : [0]);
        while (true) {
            if ($data['max'] == 0) {
                $data['max'] = 1;
            }
            $result = $data['max'] % $data['splitNumber'];
            if ($result == 0) {
                break;
            }
            $data['max']++;
        }
        return Res::ok($data);
    }
}
